﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

public class AlarmManager
{
    private List<AlarmItem> alarms = new List<AlarmItem>();
    private string iniFilePath;
    private IniHelper iniHelper;

    public IReadOnlyList<AlarmItem> Alarms => alarms.AsReadOnly();

    // 闹钟项类
    public class AlarmItem
    {
        public DateTime Time { get; set; }//闹钟时间
        public string Message { get; set; }//提示内容
        public bool IsRepeat { get; set; }//是否重复
        public bool IsPrompt { get; set; }//是否弹出提示
        public bool PromptSound { get; set; }//是否打开提示音
        public bool IsEnabled { get; set; }//是否启用
        public DateTime? LastTriggered { get; set; } // 上次触发时间，用于避免重复触发
    }

    public AlarmManager(string configPath = "alarms.ini")
    {
        iniFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, configPath);
        iniHelper = new IniHelper(iniFilePath);
    }

    //列表升序
    public void List_Sorting() {
        // 按Time属性升序排序，返回一个新的排序后的列表
        alarms = alarms.OrderBy(alarm => alarm.Time).ToList();
    }
    // 添加闹钟（您原有的方法）
    public void AddAlarmClock(int hour, int minute, string message, bool repeat, bool prompt, bool promptSound)
    {
        DateTime now = DateTime.Now;
        DateTime alarmTime = new DateTime(now.Year, now.Month, now.Day, hour, minute, 0);

        var newAlarm = new AlarmItem
        {
            Time = alarmTime,
            Message = string.IsNullOrWhiteSpace(message) ? "闹钟提醒" : message,
            IsRepeat = repeat,
            IsPrompt = prompt,
            PromptSound = promptSound,
            IsEnabled = true,
            LastTriggered = null
        };

        // 检查重复
        if (!alarms.Any(alarm =>
            alarm.Time.Hour == alarmTime.Hour &&
            alarm.Time.Minute == alarmTime.Minute))
        {
            alarms.Add(newAlarm);
        }
    }

    // 保存所有闹钟到 INI 文件
    public void SaveAlarmsToIni()
    {
        // 清除现有的所有节
        var existingSections = iniHelper.ReadSections();
        foreach (var section in existingSections)
        {
            if (section.StartsWith("Alarm_"))
            {
                iniHelper.WriteValue(section, null, null); // 删除整个节
            }
        }

        // 保存当前闹钟列表
        for (int i = 0; i < alarms.Count; i++)
        {
            string section = $"Alarm_{i}";
            var alarm = alarms[i];

            iniHelper.WriteValue(section, "Time", alarm.Time.ToString("yyyy-MM-dd HH:mm:ss"));
            iniHelper.WriteValue(section, "Message", alarm.Message);
            iniHelper.WriteValue(section, "IsRepeat", alarm.IsRepeat.ToString());
            iniHelper.WriteValue(section, "IsPrompt", alarm.IsPrompt.ToString());
            iniHelper.WriteValue(section, "PromptSound", alarm.PromptSound.ToString());
            iniHelper.WriteValue(section, "IsEnabled", alarm.IsEnabled.ToString());

            if (alarm.LastTriggered.HasValue)
            {
                iniHelper.WriteValue(section, "LastTriggered", alarm.LastTriggered.Value.ToString("yyyy-MM-dd HH:mm:ss"));
            }
            else
            {
                iniHelper.WriteValue(section, "LastTriggered", "");
            }
        }

        // 保存闹钟数量
        iniHelper.WriteValue("Config", "AlarmCount", alarms.Count.ToString());
    }

    // 从 INI 文件读取闹钟
    public void LoadAlarmsFromIni()
    {
        alarms.Clear();

        try
        {
            string countStr = iniHelper.ReadValue("Config", "AlarmCount", "0");
            if (int.TryParse(countStr, out int count))
            {
                for (int i = 0; i < count; i++)
                {
                    string section = $"Alarm_{i}";

                    string timeStr = iniHelper.ReadValue(section, "Time", "");
                    string message = iniHelper.ReadValue(section, "Message", "闹钟提醒");
                    string isRepeatStr = iniHelper.ReadValue(section, "IsRepeat", "false");
                    string isPromptStr = iniHelper.ReadValue(section, "IsPrompt", "false");
                    string promptSoundStr = iniHelper.ReadValue(section, "PromptSound", "false");
                    string isEnabledStr = iniHelper.ReadValue(section, "IsEnabled", "true");
                    string lastTriggeredStr = iniHelper.ReadValue(section, "LastTriggered", "");

                    if (DateTime.TryParse(timeStr, out DateTime alarmTime))
                    {
                        var alarm = new AlarmItem
                        {
                            Time = alarmTime,
                            Message = message,
                            IsRepeat = bool.Parse(isRepeatStr),
                            IsPrompt = bool.Parse(isPromptStr),
                            PromptSound = bool.Parse(promptSoundStr),
                            IsEnabled = bool.Parse(isEnabledStr),
                            LastTriggered = string.IsNullOrEmpty(lastTriggeredStr) ? (DateTime?)null : DateTime.Parse(lastTriggeredStr)
                        };

                        alarms.Add(alarm);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            // 处理读取错误
            Console.WriteLine($"读取闹钟配置失败: {ex.Message}");
        }
    }

    // 删除闹钟
    public void RemoveAlarm(int index)
    {
        if (index >= 0 && index < alarms.Count)
        {
            alarms.RemoveAt(index);
        }
    }

    // 获取闹钟数量
    public int GetAlarmCount()
    {
        return alarms.Count;
    }
    // 提供添加方法
    public void AddAlarm(AlarmItem newAlarm)
    {
        // 可以在这里添加验证逻辑
        if (newAlarm == null)
            throw new ArgumentNullException(nameof(newAlarm));

        alarms.Add(newAlarm);
    }
}